//
//  MainViewController.m
//  citzenWorkStation
//
//  Created by yang qing on 2018/2/9.
//  Copyright © 2018年 yang qing. All rights reserved.
//

#import "HomeViewController.h"
#import "DataSaveUtils.h"
#import "MenuController.h"
#import "UIViewController+LGSideMenuController.h"
#import "SlideViewController.h"
#import "UIColor+Hex.h"
#import <WebKit/WebKit.h>
#import "UIView+Layout.h"
#import "UIView+Toast.h"
#import "UserInfoBean.h"
#import "CommonReqManage.h"
#import "NSObject+YYModel.h"
#import "WebViewJavascriptBridge.h"
#import "LoginViewController.h"

#import "MapUtils.h"
#import <CoreLocation/CoreLocation.h>
@interface HomeViewController ()<WKNavigationDelegate,CLLocationManagerDelegate>{
    WKUserContentController* userContentController;
    WKWebView *webView;
    CLLocationManager *locatinManager;
    UserInfoBean *userInfo;
   
}
 @property WebViewJavascriptBridge* bridge;
@end

@implementation HomeViewController
int leftType = 1;//导航栏左侧按钮类型  1. 表示打开侧滑菜单 2.表示返回上页面
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initNav];
    [self startLocation];
    //添加webview
    [self initWebView];
    
}

- (void)startLocation{
    if(!locatinManager){
        locatinManager = [[CLLocationManager alloc]init];
        locatinManager.delegate = self;
        locatinManager.desiredAccuracy = kCLLocationAccuracyBest;
    }
    if([CLLocationManager locationServicesEnabled]){
      if([locatinManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
          [locatinManager requestAlwaysAuthorization];
      }else{
          NSLog(@"没有respondsToSelector");
      }
        [locatinManager startUpdatingLocation];
    }else{
        NSLog(@"定位服务不可用");
    }
}


- (void)initWebView{
    webView =[[WKWebView alloc]initWithFrame:self.view.bounds];
    webView.navigationDelegate = self;
    [self.view addSubview:webView];
//    [WebViewJavascriptBridge enableLogging];
    _bridge = [WebViewJavascriptBridge bridgeForWebView:webView];
    [_bridge setWebViewDelegate:self];
    //注册js将要调用的oc方法
    [self registerMethods:_bridge];
    
    NSURL *filePath = [[NSBundle mainBundle] URLForResource:@"dist/index.html" withExtension:nil];
    NSURLRequest *request = [NSURLRequest requestWithURL:filePath];
    [webView loadRequest:request];
    
    
//    NSString *url = @"http://0.0.0.0:8080";
//    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    
}
- (void)registerMethods:(WebViewJavascriptBridge *)brige{
    
     NSString *param = @"param";
    [_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *result = data[param];
        [self showToast:result];
        responseCallback(@"我是oc返回过去的结果数据");
    }];
    
    [_bridge registerHandler:@"getCurrentTitle" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *reslut = data[param];
        [self setTitle:reslut];
        if([reslut isEqualToString:@"爱吉林"]){
            leftType = 1;
            [self setNavLeftImg:@"nav_menu"];
        }else{
            leftType = 2;
            [self setNavLeftImg:@"nav_back"];
        }
        responseCallback(@"ok");
    }];
    
    [_bridge registerHandler:@"getBgcode" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *bgCode = [DataSaveUtils getBgCode];
        NSLog(@"调用getBgcode方法：返回%@",bgCode);
        responseCallback(bgCode);
    }];
    
    
    [_bridge registerHandler:@"startLocation" handler:^(id data, WVJBResponseCallback responseCallback) {
        [self startLocation];
        NSLog(@"startLocation 成功调用");
        responseCallback(@"ok");
    }];
    
    [_bridge registerHandler:@"getLocation" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *location;
        if(DEBUG){
            location = @"14090823.883200558,5446737.409308622";
        }else{
           location = [DataSaveUtils getLocationInfo].positionStr;
        }
        NSLog(@"调用getLocation方法：返回%@",location);
        responseCallback(location);
    }];
    
    [_bridge registerHandler:@"isLogin" handler:^(id data, WVJBResponseCallback responseCallback) {
          NSString *result=@"";
        if(userInfo){
            result = [result stringByAppendingString:userInfo.is_login];
            result = [result stringByAppendingString:@","];
            result = [result stringByAppendingString:userInfo.token];
            NSLog(@"调用isLogin方法：返回%@",result);
            responseCallback(result);
        }else{
            NSLog(@"调用isLogin方法：返回%@",result);
            responseCallback(result);
        }
    }];
    
    [_bridge registerHandler:@"isAuth" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *isAuth = @"false";
        if(userInfo){
            if(userInfo.auth == 1 || userInfo.auth ==3 ){
                isAuth = @"true";
            }else{
                isAuth = @"false";
            }
            NSLog(@"调用isAuth方法：返回%@",isAuth);
               responseCallback(isAuth);
        }else{
              responseCallback(isAuth);
        }
      
    }];
    [_bridge registerHandler:@"getUserLoginName" handler:^(id data, WVJBResponseCallback responseCallback) {
            NSString *loginName = userInfo.loginName;
            NSLog(@"调用getUserLoginName方法：返回%@",loginName);
            responseCallback(loginName);
    }];
    
    [_bridge registerHandler:@"Login" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"调用了Login方法");
        LoginViewController *loginVc = [[LoginViewController alloc]init];
        UINavigationController *navLogin = [[UINavigationController alloc]initWithRootViewController:loginVc];
        [self presentViewController:navLogin animated:YES completion:nil];
        responseCallback(@"ok");
    }];
    
    [_bridge registerHandler:@"log" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *reslut = data[param];
        NSLog(@"log显示信息：%@",reslut);
        responseCallback(@"ok");
    }];
    
    [_bridge registerHandler:@"callPhone" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *phoneNumber = data[param];
        UIWebView * callWebview = [[UIWebView alloc] init];
        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:phoneNumber]]];
        [[UIApplication sharedApplication].keyWindow addSubview:callWebview];
        responseCallback(@"ok");
    }];
}



- (void)initNav{
    //设置导航栏背景颜色
    self.navigationController.navigationBar.barTintColor =
    [UIColor colorWithHexString:ThemeColor];
    
    //设置导航栏标题文字和文字大小
    [self setNavtitle:@"爱吉林"];
    //设置两侧按钮
    [self setNavLeftImg:@"nav_menu"];
    //2. 右侧按钮
    [self setNavRightImg:@"nav_msg"];
}

- (void)menuClick{
    if(leftType == 1){
        [self openSlideMenu];
    }else if(leftType == 2){
        if([webView canGoBack]){
            [webView goBack];
    		    }
    }else{
        [self showHubAuto:@"没定义改点击事件类型"];
    }
  
}

- (void)msgClick{
//    NSString *bgCode = [DataSaveUtils getBgCode];
//    NSLog(@"调用getBgcode方法：返回%@",bgCode);
    NSLog(@"ssss");
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"tel:18600887431"]]];
    [[UIApplication sharedApplication].keyWindow addSubview:callWebview];
}

- (void)setNavtitle:(NSString *)title{
    self.navigationItem.title = title;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:20]}];
}

- (void)setNavLeftImg:(NSString *)name{
    UIButton *menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [menuButton setFrame:CGRectMake(-20.0, 0.0, 44.0, 44.0)];
    [menuButton addTarget:self action:@selector(menuClick) forControlEvents:UIControlEventTouchUpInside];
    [menuButton setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)];
    [view addSubview:menuButton];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)setNavRightImg:(NSString *)name{
    UIButton *msgButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [msgButton setFrame:CGRectMake(20.0, 0.0, 44.0, 44.0)];
    [msgButton addTarget:self action:@selector(msgClick) forControlEvents:UIControlEventTouchUpInside];
    [msgButton setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
    //添加一层包裹 更改包裹内view的位置
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)];
    [view addSubview:msgButton];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)openSlideMenu{
    SlideViewController *slideVc = (SlideViewController *)  self.sideMenuController;
    [slideVc showLeftViewAnimated];
}

- (void)closeSlideMenu{
    SlideViewController *slideVc = (SlideViewController *)  self.sideMenuController;
    [slideVc hideRightViewAnimated];
}

- (void)viewDidAppear:(BOOL)animated{
    //登录
    userInfo = [DataSaveUtils getUserInfo];
    if(userInfo){
            id userInfoStr = [userInfo yy_modelToJSONObject];
            NSString *psw = userInfo.password;
            [CommonReqManage LoginWidthParam:userInfoStr success:^(id success) {
                NSString *status =  success[@"status"];
                if([status isEqualToString:@"1"]){
                    userInfo =  [UserInfoBean yy_modelWithJSON:success[@"result"]];
                    //保存用户信息
                    userInfo.password = psw;
                    [DataSaveUtils saveUserInfo:userInfo];
//                    [self showToast:@"登录成功"];
                }else{
                    [self showTip:success[@"message"] cancelText:@"" confirmText:@"确定" Confirm:nil Cancel:nil];
                }
            } failed:^(id failure) {
                NSLog(@"首页登录失败");
            }];
    }
}

#pragma mark - WKNavigationDelegate 追踪加载过程
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"didStartProvisionalNavigation");
    [self showHub:@"加载中..."];
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    NSLog(@"didCommitNavigation");
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"didFinishNavigation");
    [self hiddenHub];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"didFailNavigation");
    [self hiddenHub];
    [self showHubAuto:@"界面加载失败"];
}



#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if([error code] == kCLErrorDenied){
        NSLog(@"访问被拒绝");
    }
    
    if([error code] == kCLErrorLocationUnknown){
        NSLog(@"无法获取位置信息");
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    NSLog(@"获取位置信息成功");
    CLLocation *lastLocation  =[locations lastObject];
    CLLocationCoordinate2D coordinate = lastLocation.coordinate;
    NSLog(@"纬度:%f 经度:%f", coordinate.latitude, coordinate.longitude);
    
//   平面坐标 @"14090823.883200558,5446737.409308622";
//   经纬度 (126.58002461877456, 43.879007779298682);
    MyPoint *p = [[MyPoint alloc] init];
    p.lat = coordinate.latitude;
    p.lon = coordinate.longitude;
    [MapUtils lonLat2Mercator:p];
    NSString *locationInfo =@"";
    locationInfo = [locationInfo stringByAppendingFormat:@"%f,%f",p.x,p.y];
    p.positionStr = locationInfo;
    
    //保存数据
    [DataSaveUtils saveLocationInfo:p];
    [manager stopUpdatingLocation];
    
    //请求网格编号
    [CommonReqManage getGridByGeo:locationInfo success:^(id success) {
         NSString *bgCode=@"";
        NSArray *data  = success[@"features"];
        if(data.count>0){
            id d2 = [data lastObject];
            id d3 = d2[@"attributes"];
            if(d3){
                  bgCode = d3[@"BGCODE"];
            }
        }
         [DataSaveUtils saveBgCode:bgCode];
    } failed:^(id faiure) {
        NSLog(@"网格编号获取失败");
    }];
}

@end
